package org.wordpress.android.comments;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.wordpress.android.R;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class CommentAdapter extends ArrayAdapter<Comment> {

    private static final int MAX_TEXT_SIZE = 40;

    private List<Comment> comments;
    private int infoViewResourceId;
    private int textViewResourceId;

    public CommentAdapter(Context context, List<Comment> comments) {
        super(context, R.layout.manage_comments, R.id.commentText, comments);
        this.comments = comments;
        this.textViewResourceId = R.id.commentText;
        this.infoViewResourceId = R.id.commentInfo;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        Comment comment = getItem(position);

        TextView text = (TextView) view.findViewById(this.textViewResourceId);
        text.setText(truncate(comment.getText()));

        TextView info = (TextView) view.findViewById(this.infoViewResourceId);
        String infoText = comment.getAuthor() + " - " + formatDate(comment.getDate());
        info.setText(infoText);

        return view;
    }

    private CharSequence formatDate(Date date) {
        String datePattern = getContext().getString(R.string.commentDateFormat);
        System.out.println("datePattern: " + datePattern);
        return DateFormatUtils.format(date, datePattern);
    }

    private CharSequence truncate(String text) {
        String substring = StringUtils.substring(text, 0, MAX_TEXT_SIZE);
        if (text.length() > MAX_TEXT_SIZE) {
            substring += "...";
        }
        return substring;
    }

    public List<Comment> getComments() {
        return this.comments;
    }

    public void setComments(List<Comment> newComments) {
        synchronized (this.comments) {
            this.comments.clear();
            this.comments.addAll(newComments);
        }
    }
}
